package com.taoym.voucher.xcx.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @coder taoym
 * @datetime 2021/6/4 18:15
 * @desc 请求切面，记录请求内容和返回内容
 */
@Aspect
@Component
@Slf4j
public class RequestAspect {

    /**
     * 定义一个切点
     */
    @Pointcut("execution (public * com.taoym.voucher.xcx.controller..*.*(..))")
    public void webLog() {
    }

    /**
     * before
     */
    @Before("webLog()")
    public void doAfter(JoinPoint joinPoint) {
        /** 接收到请求,开始记录日志 */
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();

        log.info("===请求URL:" + request.getRequestURI());
        log.info("===请求方式:" + request.getMethod());
        log.info("===请求方法:" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        Object[] args = joinPoint.getArgs();
        if (args.length != 0 && args[0] instanceof BindException) {
            log.info("===参数校验失败====请求参数：null");
        } else {
            try {
                log.info("===请求参数：" + (JSON.toJSONString(args)));
            } catch (JSONException e) {
                log.info("===本次请求为上传请求，请求参数带有文件，无法json格式化！");
            }
        }
    }

    /**
     * after
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {

    }
}
